import ffmpeg
import numpy
import cv2
import sys
import subprocess as sb




def get_video_info(in_file):
    """
    获取视频基本信息
    """
    try:
        probe = ffmpeg.probe(in_file)
        video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
        if video_stream is None:
            print('No video stream found', file=sys.stderr)
            sys.exit(1)
        return video_stream
    except ffmpeg.Error as err:
        print(str(err.stderr, encoding='utf8'))
    sys.exit(1)


if __name__ == '__main__':
    screen_cmd = ['adb', 'exec-out', 'screenrecord', '--output-format=h264', '-']
    screen_stream = sb.Popen(screen_cmd, stdout=sb.PIPE, universal_newlines=True)
    process = (
        ffmpeg.input('pipe:')
            .filter('select', 'gte(n,{})'.format(19))
            .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
            .run_async(pipe_stdin=True)
    )
    out = process.stdin.write(screen_stream.stdout)
    image_array = numpy.asarray(bytearray(out), dtype="uint8")
    image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
    cv2.imshow('frame', image)
    cv2.waitKey()
